<?php
use Illuminate\Database\Capsule\Manager as DB;

#[店铺门店管理]
class StoreController extends McommonController {

    public function init() {
        $this->model = new storeModel();
        $this->table = 'store';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[门店列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()){
            $keywords = $this->postData['keywords']??'';
            $this->model = $this->model->where('dianpu_id', $this->auth->dianpu_id);
            if(!empty($keywords)){
                $this->model = $this->model->where(function ($kQuery) use ($keywords){
                    $kQuery->where($this->primaryKey, $keywords)->orWhere('name', 'like', "%{$keywords}%");
                });
            }
        }
        return parent::indexAction($returnData); // TODO: Change the autogenerated stub
    }

    #[添加门店]
    public function addAction()
    {
        if (!$this->isPost()) {
            $prov = DB::table('area')->where('level', 1)->get();
            $city = DB::table('area')->where('level', 2)->get();
            $area = DB::table('area')->where('level', 3)->get();
            $this->_view->assign('prov', $prov->toJson());
            $this->_view->assign('city', $city->toJson());
            $this->_view->assign('area', $area->toJson());
            $dataset = $this->getTableColumn($this->table);
            $dataset['images_arr'] = [];
            $dataset['openweeks_arr'] = [];
            $dataset['members'] = [];
            $dataset['service_area_ids_arr'] = [];
            $dataset['service_area_names_arr'] = [];
            $dataset['status_text'] = '';
            $this->_view->assign('dataset', json_encode($dataset, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/edit.html');
        }else{
            $inputs = $this->postData;
            Validate::check($inputs, [
                'name'      =>['role'=>'required', 'msg'=>'门店名称'],
                'province_id' => ['role'=>'required|gt:0', 'msg'=>'所在区域省'],
                'city_id' => ['role'=>'required|gt:0', 'msg'=>'所在区域市'],
                'area_id' => ['role'=>'required|gt:0', 'msg'=>'所在区域县/区'],
            ]);
            $area = DB::table('area')
                ->where('id',  $this->postData['province_id'])
                ->orWhere('id',$this->postData['city_id'])
                ->orWhere('id',$this->postData['area_id'])
                ->pluck('name', 'id');
            $this->postData['province_name'] = $area[$this->postData['province_id']];
            $this->postData['city_name'] = $area[$this->postData['city_id']];
            $this->postData['area_name'] = $area[$this->postData['area_id']];
            $member_ids = $this->postData['member_ids'];
            $rows = $this->postData;
            $rows['created_at'] = timestamp();
            $rows['updated_at'] = timestamp();
            unset($rows['id'], $rows['deleted_at'], $rows['latitude'], $rows['longitude']);
            $this->cleanColumn($rows);
            $rows['dianpu_id'] = $this->auth->dianpu_id;
            $store_id = $this->model->insertGetId($rows);
            if ($store_id) {
                if ($member_ids && count($member_ids)){
                    $store_members_arr = [];
                    foreach ($member_ids as $member_id){
                        $store_members_arr[] = [
                            'store_id' => $store_id,
                            'member_id' => $member_id,
                        ];
                    }
                    \app\modules\Admin\models\storememberModel::query()->insert($store_members_arr);
                }
                ret(0, '添加门店成功！');
            } else {
                ret(3, '添加门店失败');
            }

        }

    }

    #[编辑门店]
    public function editAction()
    {
        if (!$this->isPost()) {
            $this->model = $this->model->where('dianpu_id', $this->auth->dianpu_id)->with(['members']);
            array_push($this->appends, ['openweeks_arr', 'service_area_names_arr']);
            $prov = DB::table('area')->where('level', 1)->get();
            $city = DB::table('area')->where('level', 2)->get();
            $area = DB::table('area')->where('level', 3)->get();
            $this->_view->assign('prov', $prov->toJson());
            $this->_view->assign('city', $city->toJson());
            $this->_view->assign('area', $area->toJson());
            parent::editAction();
        }else{
            $rows = $this->postData;
            $roles = [
                $this->primaryKey => ['role' => "required|exists:{$this->table}.{$this->primaryKey}", 'msg' => '主键'],
            ];
            try {
                Validate::check($rows, $roles);
                $area = DB::table('area')
                    ->where('id',  $this->postData['province_id'])
                    ->orWhere('id',$this->postData['city_id'])
                    ->orWhere('id',$this->postData['area_id'])
                    ->pluck('name', 'id');
                $rows['province_name'] = $area[$this->postData['province_id']];
                $rows['city_name'] = $area[$this->postData['city_id']];
                $rows['area_name'] = $area[$this->postData['area_id']];
                $member_ids = $this->postData['member_ids'];
                $rows['updated_at'] = timestamp();
                unset($rows['created_at'], $rows['deleted_at'], $rows['latitude'], $rows['longitude']);
                $this->cleanColumn($rows);
                if ($this->model->where('dianpu_id', $this->auth->dianpu_id)->where($this->primaryKey, $rows[$this->primaryKey])->update($rows) !== FALSE) {
                    if(count($member_ids)){
                        $db_member_ids = \app\modules\Admin\models\storememberModel::query()->where('store_id', $rows['id'])->pluck('member_id')->toArray();
                        $member_ids_insert = array_diff($member_ids,$db_member_ids);
                        $member_ids_del = array_diff($db_member_ids,$member_ids);
                        if (count($member_ids_del)){
                            \app\modules\Admin\models\storememberModel::query()->where('store_id', $rows['id'])->whereIn('member_id', $member_ids_del)->delete();
                        }
                        if (count($member_ids_insert)){
                            $store_members_arr = [];
                            foreach ($member_ids_insert as $member_id){
                                $store_members_arr[] = [
                                    'store_id' => $rows['id'],
                                    'member_id' => $member_id,
                                ];
                            }
                            \app\modules\Admin\models\storememberModel::query()->insert($store_members_arr);
                        }
                    }
                    ret(0, '修改门店成功！');
                } else {
                    ret(3, '修改门店失败');
                }
            }catch (Exception $e){
                ret($e->getCode(), $e->getMessage());
            }
        }
    }

    #[回收门店]
    public function dropAction()
    {
        $store_id = $this->get('id', 0);
        if($store_id){
            $store = $this->model->where('dianpu_id', $this->auth->dianpu_id)->where($this->primaryKey, $store_id)->first();
            if(!$store){
                ret(3, '门店不存在或者已被回收');
            }
            $store->status = 0;
            $store->updated_at = timestamp();
            $store->deleted_at = timestamp();
            if($store->save()){
                ret(0, '删除门店成功！');
            }else{
                ret(1, '删除门店失败');
            }
        }else{
            ret(2, '参数出错！');
        }
    }

    #[销毁门店]
    public function deleteAction()
    {

    }

    #[还原门店]
    public function restoreAction()
    {
        $this->model = $this->model->where('dianpu_id', $this->auth->dianpu_id);
        parent::restoreAction(); // TODO: Change the autogenerated stub
    }

    #[切换门店状态]
    public function togglestatusAction()
    {
        if($this->isPost()){
            $store_id = $this->get('id', 0);
            if($store_id){
                $store = $this->model->where('dianpu_id', $this->auth->dianpu_id)->where($this->primaryKey, $store_id)->first();
                if(!$store){
                    ret(3, '门店不存在或者已被回收');
                }
                if($store->status === 1){
                    $store->status = 0;
                }else{
                    $store->status = 1;
                }
                $store->updated_at = timestamp();
                if($store->save()){
                    ret(0, '切换门店状态成功！');
                }else{
                    ret(1, '切换门店状态失败');
                }
            }else{
                ret(2, '参数出错');
            }
        }else{
            ret(4, '请求错误');
        }
    }

    #[获取可成为管理员的用户列表]
    public function getmemberlistAction()
    {
        if($this->isPost()){
            $type     = $this->get('keywordsType');
            $keywords = $this->get('keywords');
            $master_ids = \app\modules\Admin\models\storememberModel::query()->groupBy('member_id')->pluck('member_id')->toArray();
            if(count($master_ids) > 2000){
                $storemember_table = (new \app\modules\Admin\models\storememberModel())->getTable();
                $member_table = (new memberModel())->getTable();
                $query = memberModel::query()
                    ->leftjoin($storemember_table, "{$member_table}.id", '=', "{$storemember_table}.member_id")
                    ->where("{$member_table}.status", '=', 'normal')->where(function ($query) use($member_table){
                        $query->whereNull("{$member_table}.deleted_at")->orWhereDate("{$member_table}.deleted_at", '<=', '0000-00-00');
                    })->whereNull("{$storemember_table}.store_id")->select([
                        "{$member_table}.id",
                        "{$member_table}.avatar",
                        "{$member_table}.nickname",
                        "{$member_table}.phone",
                        "{$storemember_table}.store_id",
                    ])->groupBy("{$member_table}.id");
                if (!empty($keywords)) {
                    switch ($type){
                        case 'id':
                            $query->where("{$member_table}.id", $keywords);
                            break;
                        case 'nickname':
                            $query->where("{$member_table}.nickname", 'like', "%{$keywords}%");
                            break;
                        case 'phone':
                            $query->where("{$member_table}.phone", 'like', "%{$keywords}%");
                            break;
                    }
                }
                $querySql = $query->toSql();
                $total = DB::table(DB::raw("($querySql) as unionSearch"))->mergeBindings($query->getQuery())->count();
                $query = $query->orderBy("{$member_table}.id", 'DESC');
            }else{
                $query = memberModel::query()->where('status', '=', 'normal')->where(function ($query){
                    $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
                })->whereNotIn('id', $master_ids);
                if (!empty($keywords)) {
                    switch ($type){
                        case 'id':
                            $query->where("id", $keywords);
                            break;
                        case 'nickname':
                            $query->where("nickname", 'like', "%{$keywords}%");
                            break;
                        case 'phone':
                            $query->where("phone", 'like', "%{$keywords}%");
                            break;
                    }
                }
                $total = $query->count();
                $query = $query->select([
                    "id",
                    "avatar",
                    "nickname",
                    "phone",
                ]);
            }
            $page = $this->get('page', 1);
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $query = $query->offset($offset)->limit($limit);
            $rows = $query->get()->makeHidden(['nickname_hide'])->append('level_info');
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/getmemberlist.html');
        }
    }

    #[获取行政地区]
    public function getserviceareaAction()
    {
        $store_id = $this->get('id', 0);
        $service_area_names_arr = [];
        if($store_id){
            $selectAreas = $this->model->where('dianpu_id', $this->auth->dianpu_id)->where($this->primaryKey, $store_id)->select(['service_area_ids'])->first()->makeHidden(['status_text', 'service_area_ids_arr', 'images_arr'])->append('service_area_names_arr')->toArray();
            $service_area_names_arr = $selectAreas['service_area_names_arr'];
        }
        $this->_view->assign('selectAreas', json_encode($service_area_names_arr, JSON_UNESCAPED_UNICODE));
        $this->_view->assign('allAreaTree', $this->areaTree()->toJson());
        $this->_view->display( strtolower($this->controller) . '/getarea.html');
    }

    private function areaTree()
    {
        $query   = DB::table('area')->where('pid', '=', '0');
        $rows    = $query->select('id', 'name', 'pid', 'level')->get();
        $allCity = DB::table('area')->where('level', 2)->select('id', 'pid', 'name', 'level')->get();
        $allArea = DB::table('area')->where('level', 3)->select('id', 'pid', 'name', 'level')->get();
        foreach ($rows as $k1 => &$v1) {
            $v1->children = [];
            foreach ($allCity as $k2 => &$v2) {
                if ($v2->pid == $v1->id) {
                    $v2->children = [];
                    foreach ($allArea as $k3 => &$v3) {
                        if ($v3->pid == $v2->id) {
                            array_push($v2->children, $v3);
                        }
                    }
                    array_push($v1->children, $v2);
                }
            }
        }
        return $rows;
    }
}
